package com.wk.net.heartbeat.handler.receivers;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.wk.net.heartbeat.handler.FailedSourceException;
import com.wk.net.heartbeat.handler.HeartbeatMessage;
import com.wk.net.heartbeat.handler.HeartbeatReceiver;


public class TcpReceiver implements HeartbeatReceiver {
	public TcpReceiver(int port) {
		this.port = port;
	}

	public void listen() throws IOException {
		listener = new ServerSocket(port);
	}

	@Override
	public HeartbeatMessage accept() throws FailedSourceException, IOException {
		Socket client = listener.accept();
		try {
			// 引用javadoc：Socket.getInputStream()
			// Closing the returned InputStream will close the associated
			// socket.
			return new HeartbeatMessage(client.getInetAddress().getHostAddress(), client.getInputStream());
		} catch (IOException e) {
			throw new FailedSourceException();
		}
	}

	public void close() {
		try {
			listener.close();
		} catch (IOException e) {
		}
	}

	private ServerSocket listener;
	private int port;
}
